package ai.people.platform.oss.aspect;

import ai.people.platform.oss.config.OssClientContextHolder;
import com.aliyun.oss.OSS;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 关闭切面
 *
 * @author yuanqinglong
 * @date 2022/4/28 15:24
 */
@Aspect
@Component
public class ShutdownOssClientAspect {

    private final Logger logger = LoggerFactory.getLogger(ShutdownOssClientAspect.class);

    @Pointcut(value = "execution(* ai.people.platform.oss.service.impl.AliOssStorageServiceImpl.uploadPicture(..))||" +
                      "execution(* ai.people.platform.oss.service.impl.AliOssStorageServiceImpl.write(..))")
    public void shutdownCut() {
    }


    /**
     * 关闭连接
     *
     * @param point 点
     * @return {@link Object}
     * @throws Throwable 异常
     */
    @Around("shutdownCut()")
    public Object shutdownHook(ProceedingJoinPoint point) throws Throwable {
        Object proceed = point.proceed();
        this.closeOssClient();
        return proceed;
    }


    /**
     * 异常通知
     */
    @AfterThrowing(pointcut = "shutdownCut()", throwing = "ex")
    public void exceptionNotification(JoinPoint joinPoint, Exception ex) {
        logger.error("business exception notification ", ex);
        this.closeOssClient();
    }


    /**
     * 关闭oss客户
     */
    private void closeOssClient() {
        OSS ossClient = OssClientContextHolder.getRequestThreadHolder();
        logger.info("start the execution to close the client {}", ossClient);
        try {
            if (Objects.isNull(ossClient)) {
                return;
            }
            ossClient.shutdown();
        } catch (Exception e) {
            logger.error("close client exception {}", e.getMessage());
        } finally {
            OssClientContextHolder.resetRequestThreadHolder();
        }
        logger.info("client closed successfully");
    }

}
